package com.example.userservice.permission.checker;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.userservice.entity.User;
import com.example.userservice.entity.vo.UserVo;
import com.example.userservice.mapper.UserMapper;
import com.example.userservice.permission.PermissionChecker;
import com.example.userservice.util.UserConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

@Component("user")
public class UserPermission implements PermissionChecker {
    @Autowired
    UserMapper userMapper;
    //获取用户列表
    @Override
    public List<UserVo> getUsers(Long currentUserId) {
        UserVo userVo = UserConverter.getUserVoFromUser(userMapper.selectByUserId(currentUserId));
        return currentUserId == null ? Collections.emptyList() : Collections.singletonList(userVo);
    }
    //获取指定用户信息
    @Override
    public UserVo getUser(Long currentUserId, Long targetUserId) {
        if (currentUserId.equals(targetUserId)){
            return UserConverter.getUserVoFromUser(userMapper.selectByUserId(currentUserId));
        }
        return null;
    }
    //修改用户信息
    @Override
    public Boolean updateUser(Long currentUserId, Long targetUserId, User user) {
        if (currentUserId.equals(targetUserId)){
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("user_id", targetUserId)
                    .set("phone",user.getPhone())
                    .set("email",user.getEmail());
            return userMapper.update(null, updateWrapper) > 0;
        }
        return false;
    }
    //重置密码
    @Override
    public Boolean resetPassword(Long currentUserId, User user) {
        Long targetUserId = userMapper.selectUserIdByUserName(user.getUserName());
        if (currentUserId.equals(targetUserId)){
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("user_id", targetUserId).set("password", user.getPassword());
            return userMapper.update(null, updateWrapper) > 0;
        }
        return false;
    }
}
